import Ajv from 'ajv'
import addFormats from 'ajv-formats'

const ajv = new Ajv({ strictTypes: false })
addFormats(ajv)

// JSON Schema定义
export const formSchema = {
  type: 'object',
  properties: {
    fields: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          id: { type: 'string' },
          type: { 
            type: 'string',
            enum: ['input', 'textarea', 'select', 'radio', 'checkbox', 'date', 'time']
          },
          label: { type: 'string' },
          placeholder: { type: 'string' },
          required: { type: 'boolean' },
          defaultValue: { type: ['string', 'number', 'boolean'] },
          rules: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                validator: { type: 'string' },
                message: { type: 'string' }
              },
              required: ['validator']
            }
          },
          options: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                label: { type: 'string' },
                value: { type: ['string', 'number'] }
              },
              required: ['label', 'value']
            }
          }
        },
        required: ['id', 'type', 'label']
      }
    },
    layout: { type: 'object' },
    rules: { type: 'object' }
  },
  required: ['fields']
}

export const validateFormSchema = ajv.compile(formSchema)

export const validateField = (field: any): boolean => {
  const fieldSchema = {
    type: 'object',
    properties: formSchema.properties.fields.items.properties,
    required: formSchema.properties.fields.items.required
  }
  
  const validate = ajv.compile(fieldSchema)
  return validate(field)
}

export const exportToJSONSchema = (formSchema: any): any => {
  // 将内部schema转换为标准JSON Schema
  const jsonSchema = {
    type: 'object',
    properties: {},
    required: []
  }

  formSchema.fields.forEach((field: any) => {
    let fieldSchema: any = { type: 'string' }

    switch (field.type) {
      case 'number':
        fieldSchema = { type: 'number' }
        break
      case 'boolean':
        fieldSchema = { type: 'boolean' }
        break
      case 'array':
        fieldSchema = { type: 'array', items: { type: 'string' } }
        break
    }

    if (field.required) {
      jsonSchema.required.push(field.id)
    }

    jsonSchema.properties[field.id] = fieldSchema
  })

  return jsonSchema
}